import { uniqueId } from '@/Editor/utils/uniqueId';
import { Button, Space } from 'antd';
import React, { useContext, type CSSProperties } from 'react';
import { GlobalContext } from '../config';
import { INode } from '../type';

export default function TreeNode(props: {
  data: INode;
  style?: CSSProperties;
}) {
  const {
    data,
    style = {
      paddingLeft: 0,
    },
  } = props;
  const { modalRef, dispatch } = useContext(GlobalContext);

  if (!data) return null;
  return (
    <div style={style}>
      <div style={{ paddingTop: 10, paddingBottom: 10 }}>
        <Space>
          {`-${data.name}`}
          <Button
            size="small"
            onClick={() => {
              modalRef.current?.open({
                type: 'edit',
                record: { id: data.id, name: data.name },
                onSuccess: (data: INode) => {
                  dispatch({
                    type: 'update',
                    payload: data,
                  });
                },
              });
            }}
          >
            修改
          </Button>
          <Button
            size="small"
            onClick={() => {
              const toAddId = uniqueId();
              modalRef.current?.open({
                type: 'add',
                record: { id: toAddId, name: toAddId },
                onSuccess: (formData: INode) => {
                  dispatch({
                    type: 'add',
                    payload: {
                      ...formData,
                      parentId: data.id,
                    },
                  });
                },
              });
            }}
          >
            添加
          </Button>
          <Button
            size="small"
            onClick={() => {
              dispatch({
                type: 'delete',
                payload: data.id,
              });
            }}
          >
            删除
          </Button>
        </Space>
      </div>
      {data.children?.map((treeNode) => (
        <TreeNode
          key={treeNode.id}
          data={treeNode}
          style={{ paddingLeft: Number(style.paddingLeft) + 40 }}
        />
      ))}
    </div>
  );
}
